<template>
  <div class="content">
    <div class="searchinp">
      <span @click="back" class="totrain"></span>
      <div class="input_box">
        <!-- <img class="btn_img" src="../assets/search.png" alt="" /> -->
        <input type="text" v-model="search_val" />
      </div>

      <button @click="get_search">搜索</button>
    </div>
    <div class="history">
      <p class="note">
        <span>历史搜索</span>
        <button @click="empty">
          <van-icon class="icon" name="delete-o" />
          <span>清除记录</span>
        </button>
      </p>
      <ul v-if="historyList.length > 0">
        <li
          v-for="(item, index) in historyList"
          :key="index"
          @click="goSearchDetail(item)"
        >
          {{ item }}
        </li>
      </ul>
      <p
        v-else
        style="
          text-align: center;
          margin: 0 auto;
          font-size: 16px;
          margin-top: 20px;
        "
      >
        暂无搜索记录
      </p>
    </div>
  </div>
</template>

<script>
export default {
  name: "Search",
  data() {
    return {
      search_val: "", //搜索的内容
      historyList: [], //历史搜索记录，存本地
    };
  },
  mounted() {
    //如果本地存储的数据historyList有值，直接赋值给data中的historyList
    if (JSON.parse(localStorage.getItem("historyList"))) {
      this.historyList = JSON.parse(localStorage.getItem("historyList"));
    }
  },
  methods: {
    // 搜索
    get_search() {
      if (this.search_val == "") {
        // this.$toast("请输入搜索内容");
        this.$notify({ type: "primary", message: "请输入搜索内容" });
        return false;
      } else {
        // 没有搜索记录，把搜索值push进数组首位，存入本地
        if (!this.historyList.includes(this.search_val)) {
          this.historyList.unshift(this.search_val);
          localStorage.setItem("historyList", JSON.stringify(this.historyList));
        } else {
          //有搜索记录，删除之前的旧记录，将新搜索值重新push到数组首位
          let i = this.historyList.indexOf(this.search_val);
          this.historyList.splice(i, 1);
          this.historyList.unshift(this.search_val);
          localStorage.setItem("historyList", JSON.stringify(this.historyList));
        }
        //跳转到搜索结果页
        this.$router.push({
          path: "/home", //home是列表页
          query: {
            keyword: this.search_val,
          },
        });
      }
    },
    //点击历史搜索，跳转搜索结果页
    goSearchDetail(title) {
      this.$router.push({
        path: "/home",
        query: {
          keyword: title,
          //   search_val: title,
        },
      });
    },

    //清空历史搜索记录
    empty() {
      this.$notify({ type: "success", message: "清空历史搜索成功" });
      localStorage.removeItem("historyList");
      this.historyList = [];
    },
  },
};
</script>

<style lang="scss" scoped>

</style>